package com.rul.mars.product.controller;

import cn.hutool.core.bean.BeanUtil;
import com.rul.mars.common.api.CommonPage;
import com.rul.mars.common.api.CommonResult;
import com.rul.mars.mbg.domain.ProductDetail;
import com.rul.mars.mbg.model.Product;
import com.rul.mars.product.service.ProductService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 商品服务接口
 *
 * @author RuL
 */
@Api(tags = "ProductController", description = "商品服务接口")
@RestController
@RequestMapping(path = "/product")
public class ProductController {

    @Autowired
    private ProductService productService;

    /**
     * 根据商品ID查询商品详情
     *
     * @param id 商品ID
     * @return 商品详情
     */
    @ApiOperation("根据商品ID查询商品详情")
    @GetMapping("/detail/{id}")
    public CommonResult<ProductDetail> detail(@PathVariable(value = "id") Long id) {

        ProductDetail detail = productService.detail(id);
        return CommonResult.success(detail);
    }

    /**
     * 按关键字分页搜索商品
     *
     * @param keywords 关键字
     * @param pageNum  页号
     * @param pageSize 页面大小
     * @return 按关键字搜索到的商品详细信息
     */
    @ApiOperation("搜索商品")
    @ApiImplicitParam(name = "sort", value = "排序字段:0->按相关度；1->按新品；2->按销量；3->价格从低到高；4->价格从高到低",
            defaultValue = "0", allowableValues = "0,1,2,3,4", paramType = "query", dataType = "integer")
    @GetMapping("/search")
    public CommonResult<CommonPage<ProductDetail>> search(@RequestParam("keywords") String keywords,
                                                          @RequestParam(required = false, defaultValue = "1") Integer pageNum,
                                                          @RequestParam(required = false, defaultValue = "10") Integer pageSize,
                                                          @RequestParam(required = false, defaultValue = "0") Integer sort) {
        List<Product> products = productService.search(keywords, pageNum, pageSize, sort);
        //转为ProductDetail
        List<ProductDetail> details = products.stream()
                .map(item -> BeanUtil.copyProperties(item, ProductDetail.class))
                .collect(Collectors.toList());
        return CommonResult.success(CommonPage.restPage(details));
    }

}
